"""
定时任务调度器
"""
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from loguru import logger

from config.settings import (
    FETCH_INTERVAL_MINUTES, 
    DAILY_FETCH_TIME, 
    TRADING_HOURS,
    STOCK_BASIC_FETCH_TIME,
    DATA_CLEANUP_TIME,
    REALTIME_DATA_KEEP_DAYS,
    DAILY_DATA_KEEP_DAYS
)
from data_fetcher.stock_info_fetcher import update_stock_basic_info
from data_fetcher.daily_data_fetcher import update_daily_data, update_data_from_config
from data_fetcher.realtime_data_fetcher import fetch_and_save_realtime_data
from utils.db_utils import clear_old_data

class TaskScheduler:
    """定时任务调度器"""
    
    def __init__(self):
        self.scheduler = BackgroundScheduler()
        logger.info("初始化任务调度器...")
    
    def setup_jobs(self):
        """设置定时任务"""
        # 1. 每个工作日执行一次，获取当日股票交易数据
        daily_time = DAILY_FETCH_TIME.split(":")
        self.scheduler.add_job(
            update_daily_data,
            CronTrigger(
                day_of_week='mon-fri',  # 只在周一到周五执行
                hour=daily_time[0],
                minute=daily_time[1]
            ),
            id='daily_data_job',
            name='每日股票交易数据更新',
            replace_existing=True
        )
        logger.info(f"已设置每日交易数据更新任务，执行时间: {DAILY_FETCH_TIME}（周一至周五）")
        
        # 2. 在交易时间内每隔N分钟执行一次，获取实时股票交易数据
        # 上午场
        morning_start = TRADING_HOURS['MORNING_START'].split(":")
        morning_end = TRADING_HOURS['MORNING_END'].split(":")
        self.scheduler.add_job(
            fetch_and_save_realtime_data,
            CronTrigger(
                day_of_week='mon-fri',
                hour=f"{morning_start[0]}-{morning_end[0]}",
                minute=f"*/{FETCH_INTERVAL_MINUTES}"
            ),
            id='realtime_data_job_morning',
            name='实时股票交易数据更新（上午）',
            replace_existing=True
        )
        logger.info(f"已设置实时数据更新任务（上午），执行时间: {TRADING_HOURS['MORNING_START']}-{TRADING_HOURS['MORNING_END']}，间隔: {FETCH_INTERVAL_MINUTES}分钟")
        
        # 下午场
        afternoon_start = TRADING_HOURS['AFTERNOON_START'].split(":")
        afternoon_end = TRADING_HOURS['AFTERNOON_END'].split(":")
        self.scheduler.add_job(
            fetch_and_save_realtime_data,
            CronTrigger(
                day_of_week='mon-fri',
                hour=f"{afternoon_start[0]}-{afternoon_end[0]}",
                minute=f"*/{FETCH_INTERVAL_MINUTES}"
            ),
            id='realtime_data_job_afternoon',
            name='实时股票交易数据更新（下午）',
            replace_existing=True
        )
        logger.info(f"已设置实时数据更新任务（下午），执行时间: {TRADING_HOURS['AFTERNOON_START']}-{TRADING_HOURS['AFTERNOON_END']}，间隔: {FETCH_INTERVAL_MINUTES}分钟")
        
        # 3. 每个工作日执行一次，获取股票基础信息
        basic_fetch_time = STOCK_BASIC_FETCH_TIME.split(":")
        self.scheduler.add_job(
            update_stock_basic_info,
            CronTrigger(
                day_of_week='mon-fri', 
                hour=basic_fetch_time[0], 
                minute=basic_fetch_time[1]
            ),
            id='stock_info_job',
            name='每日股票基础信息更新',
            replace_existing=True
        )
        logger.info(f"已设置股票基础信息更新任务，执行时间: {STOCK_BASIC_FETCH_TIME}（周一至周五）")

        # 4. 每30分钟更新一次历史股票交易数据
        self.scheduler.add_job(
            update_data_from_config,
            IntervalTrigger(minutes=30),
            id='historical_data_job',
            name='历史股票交易数据更新',
            replace_existing=True
        )
        logger.info("已设置历史股票交易数据更新任务，执行间隔: 30分钟")

        # 5. 每天执行一次，清理过期数据
        cleanup_time = DATA_CLEANUP_TIME.split(":")
        self.scheduler.add_job(
            clear_old_data,
            CronTrigger(
                hour=cleanup_time[0],
                minute=cleanup_time[1]
            ),
            kwargs={
                'realtime_days': REALTIME_DATA_KEEP_DAYS,
                'daily_days': DAILY_DATA_KEEP_DAYS
            },
            id='data_cleanup_job',
            name='过期数据清理',
            replace_existing=True
        )
        logger.info(f"已设置数据清理任务，执行时间: {DATA_CLEANUP_TIME}，保留实时数据: {REALTIME_DATA_KEEP_DAYS}天，每日数据: {DAILY_DATA_KEEP_DAYS}天")

    def start(self):
        """启动调度器"""
        try:
            self.setup_jobs()
            self.scheduler.start()
            logger.info("任务调度器已启动")
        except Exception as e:
            logger.error(f"启动任务调度器失败: {e}")
            raise
    
    def shutdown(self):
        """关闭调度器"""
        try:
            self.scheduler.shutdown()
            logger.info("任务调度器已关闭")
        except Exception as e:
            logger.error(f"关闭任务调度器失败: {e}")
    
    def get_jobs(self):
        """获取所有定时任务"""
        return self.scheduler.get_jobs()


# 单例模式
_scheduler = None

def get_scheduler():
    """获取调度器实例"""
    global _scheduler
    if _scheduler is None:
        _scheduler = TaskScheduler()
    return _scheduler 